<template>
    <ul>
        <p>
            <span>
                <span @click="handleExpand(true)" v-if="data[childrenKey] && !data.expand">+</span>
                <span @click="handleExpand(false)" v-if="data[childrenKey] && data.expand">-</span>
            </span>
            <icheckbox v-if="showCheckbox" :value="data.checked" @input="handleCheck"></icheckbox>
            {{data.title}}
        </p>

        <div v-if="data[childrenKey] && data[childrenKey].length">
            <niubiNode :data="item"
                       :key="index"
                       :show-checkbox="showCheckbox"
                       v-if="data.expand"
                       v-for="(item, index) in data[childrenKey]">
            </niubiNode>
        </div>
    </ul>
</template>

<script>
    import icheckbox from '../../components/checkbox/checkbox.vue'

    export default {
        name: 'niubiNode',
        inject: ['childrenKey'],
        components: {
            icheckbox
        },
        props: {
            data: {
                type: Object,
                default() {
                    return {}
                }
            },
            showCheckbox: {
                type: Boolean,
                default: false
            }
        },
        methods: {
            handleCheck(val) {
                this.$set(this.data, 'checked', val)
                if (this.data[this.childrenKey] && this.data[this.childrenKey].length) {
                    this.updateDownChildren(this.data[this.childrenKey], val)
                }
            },
            handleExpand(status) {
                this.$set(this.data, 'expand', status)
            },
            updateDownChildren(arr, status) {
                arr.forEach(item => {
                    this.$set(item, 'checked', status)
                    if (item[this.childrenKey] && item[this.childrenKey].length) {
                        this.updateDownChildren(item[this.childrenKey], status)
                    }
                })
            }
        },
        watch: {
            data: {
                handler(newVal) {
                    if (this.data[this.childrenKey] && this.data[this.childrenKey].length) {
                        const boolean = this.data[this.childrenKey].every(item => item.checked)
                        this.$set(this.data, 'checked', boolean)
                    }
                },
                deep: true,
                immediate: false
            }
        }
    }
</script>

<style lang='less'>

</style>
